/**
 * 
 */
package cn.gov.msa.interceptor;

import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.gov.msa.collection.AppLdapService;
import cn.gov.msa.collection.LdapService;
import cn.gov.msa.model.UserDetail;
import cn.gov.msa.service.UserDetailService;
import cn.gov.msa.util.PropertiesTools;
import cn.gov.msa.util.RedisUtils;
import net.sf.json.JSONObject;

/**
 * @author Administrator
 *
 */
public class LoginInterceptor implements HandlerInterceptor {
	
	private Logger logger = Logger.getLogger(LoginInterceptor.class);
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	 
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Autowired
	UserDetailService userDetailService;
	RedisUtils redis = new RedisUtils();
	boolean flag  = false;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        //获取请求的URL  
        String url = request.getRequestURI();  
        String redirectUrl = null;
        //URL:login.jsp是公开的;这个demo是除了login.jsp是可以公开访问的，其它的URL都进行拦截控制  
        if(url.indexOf("login.html")>=0){  
            return true;  
        }  
        if(url.indexOf("login.do")>=0){  
            return true;  
        } 

        if(url.indexOf("finduser.do")>=0){  
            return true;  
        } 
        if(url.indexOf("amanuensis")>=0){   //给文书html放行，防止生成文书出错
            return true;  
        }
        if(url.indexOf("getapplyinfo.do")>=0){   //给文书html放行，防止生成文书出错
            return true;  
        }
        if(url.indexOf("getbusinessinfo.do")>=0){   //给文书html放行，防止生成文书出错
            return true;  
        }
        if(url.indexOf("getmaterialinfo.do")>=0){   //给文书html放行，防止生成文书出错
            return true;  
        }
        if(url.indexOf("getcorrectioninfo.do")>=0){   //给文书html放行，防止生成文书出错
            return true;  
        }
        if(url.indexOf("getacceptinfo.do")>=0){   //给文书html放行，防止生成文书出错
            return true;  
        }
        if(url.indexOf("getlastopinion.do")>=0){   //给文书html放行，防止生成文书出错
            return true;  
        }
        if(url.indexOf("getshipinfo.do")>=0){   //给文书html放行，防止生成文书出错
            return true;  
        }
        //获取Session  
        HttpSession session = request.getSession();  
        String userid  = null;
        String token = request.getParameter("TOKEN");
        if(null!= token) {
        		UserDetail userDetail = (UserDetail) redis.hget("app",token);
        		if(null!=userDetail) {
        			session.setAttribute("userid", userDetail.getUserid());
        			session.setAttribute("userDetail", userDetail);
        			return true;
        		}else {
        			userid = AppLdapService.getUserDetail(token, 0).getUserid();
        		}
    			redirectUrl = PropertiesTools.readProperties("app.login.url");
        }else {
        	userid= (String) session.getAttribute("userid");
        	if(userid==null) {
        		Enumeration<String> en = request.getHeaderNames();
       	        while (en.hasMoreElements()) {
       				String headerName = (String) en.nextElement();
       				if("OAM_REMOTE_USER".equals(headerName)) {
       					userid= request.getHeader(headerName);
       				}
       			}
        	}
        	redirectUrl = PropertiesTools.readProperties("login.url");
        }
    	 
        logger.info("userid:"+userid);
        logger.info("token:"+token);
        if(userid != null){  
        	session.setAttribute("userid", userid);
        	UserDetail userDetail4A = null;
        	try{
        		userDetail4A = (UserDetail)session.getAttribute("userDetail");  
        	}
        	catch(Exception e){
        		e.printStackTrace();
        	}
			if (userDetail4A == null) {
				UserDetail userDetail = LdapService.getUserDetail(userid, 1);
				logger.info("4a用户："+JSONObject.fromObject(userDetail));
				if(userDetail.getUserid() != null){
					flag = true;
					if(null!=token)
						redis.hset("app",token, userDetail);
					session.setAttribute("userDetail", userDetail);
				}
			}else {
				flag = true;
			}
        }  
        if(flag) {
        	return true;
        }else {
        
	        if(null!=token) {
	        	response.setCharacterEncoding("UTF-8");
	            response.getWriter().write("{\"result\":\"-1\",\"info\":\"未登录\"}");
	        }else {
	        	//不符合条件的，跳转到登录界面  
	        	response.sendRedirect(redirectUrl);//上海测试环境
	        }
	        return false;
        }
	}

}
